package example.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import example.common.Constant;
import example.common.Result;
import example.dto.SecondmentInfoDTO;
import example.dto.StateDTO;
import example.dto.TipDTO;
import example.entity.SecondmentContentInfo;
import example.entity.TaskList;
import example.entity.UserInfo;
import example.mapper.*;
import example.service.ISecondmentContentInfoService;
import example.vo.DepartmentInfoVO;
import example.vo.PageVO;
import example.vo.SecondmentBodyVO;
import example.vo.SecondmentInfoVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class SecondmentContentInfoServiceImpl implements ISecondmentContentInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private TaskListMapper taskListMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private SecondmentHeadInfoMapper secondmentHeadInfoMapper;

    @Resource
    private SecondmentContentInfoMapper secondmentContentInfoMapper;

    @Override
    public void save(SecondmentContentInfo secondmentExcelInfo) {
        secondmentContentInfoMapper.save(secondmentExcelInfo);
    }
    @Override
    public int checkSecondmentContentExists(SecondmentContentInfo secondmentExcelInfo){
        return  secondmentContentInfoMapper.checkSecondmentContentExists(secondmentExcelInfo);
    }

    @Override
    public Result listSecondmentInformation(SecondmentInfoDTO secondmentInfoDTO) {
        //获取登录用户所属部门级别
        Long levelId = secondmentInfoDTO.getLevelId();
        //获取创建该部门的部门级别
        String createDepartmentName = secondmentInfoDTO.getCreateDepartmentName();
        Long cId = departmentMapper.getLevelIdByName(createDepartmentName);
        PageHelper.startPage(secondmentInfoDTO.getPageNum(), secondmentInfoDTO.getPageSize());
        List<SecondmentInfoVO> secondmentInfoVOList = null;

        if (levelId == 1 || (levelId == 2 && cId == 2)) {
            //如果是一级部门或二级部门且创建他的也是二级部门，获取全部信息
            secondmentInfoVOList = secondmentContentInfoMapper.getFieldsValueBySecondmentId(secondmentInfoDTO);
        } else {
            //仅获取该部门相关的信息
            secondmentInfoVOList = secondmentContentInfoMapper.getFieldsValueBySecondmentIdAndName(secondmentInfoDTO);
        }

        PageInfo<SecondmentInfoVO> pageInfo = new PageInfo<>(secondmentInfoVOList);
        List<SecondmentBodyVO> secondmentInfoVOS = new ArrayList<>();
        for (SecondmentInfoVO secondmentInfoVO : secondmentInfoVOList) {
            Map afterValue = JSON.parseObject(secondmentInfoVO.getFieldsValue(), Map.class);
            SecondmentBodyVO secondmentBodyVO = new SecondmentBodyVO();

            afterValue.put("9",calculateDateRange(secondmentInfoVO.getSecondmentDate(),secondmentInfoVO.getSecondmentLastTime().replaceAll("[^0-9]","")));
            //secondmentBodyVO.setId(secondmentInfoVO.getId());
            afterValue.put("id", secondmentInfoVO.getId());
            afterValue.put("state", secondmentInfoVO.getState());
            afterValue.put("tips", secondmentInfoVO.getTips());
            afterValue.put("confirm", secondmentInfoVO.getConfirm());
            afterValue.put("endDate", getEndTime(secondmentInfoVO.getSecondmentDate(),secondmentInfoVO.getSecondmentLastTime().replaceAll("[^0-9]","")));
            secondmentBodyVO.setBodyMap(afterValue);
            secondmentInfoVOS.add(secondmentBodyVO);
        }
        PageVO pageVO = new PageVO();
        pageVO.setSecondmentBodyVOList(secondmentInfoVOS);
        pageVO.setTotal(pageInfo.getTotal());
        return Result.ok(pageVO);
    }
    //计算借调起止时间
    public  String calculateDateRange(String startDateStr, String monthsToAddStr) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        // 解析开始日期字符串
        LocalDate startDate = LocalDate.parse(startDateStr, formatter);

        // 尝试解析月份数并转换为整数
        try {
            int monthsToAdd = Integer.parseInt(monthsToAddStr);

            // 计算结束日期
            LocalDate endDate = startDate.plusMonths(monthsToAdd);

            // 格式化并拼接开始和结束日期
            return startDate.format(formatter) + " 至 " + endDate.format(formatter);

        } catch (NumberFormatException e) {
            // 如果月份数不是有效的整数，则返回错误消息
            return "无效的月份数：" + monthsToAddStr;
        }
    }
    //获取借调结束时间
    public  String getEndTime(String startDateStr, String monthsToAddStr) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        // 解析开始日期字符串
        LocalDate startDate = LocalDate.parse(startDateStr, formatter);

        // 尝试解析月份数并转换为整数
        try {
            int monthsToAdd = Integer.parseInt(monthsToAddStr);

            // 计算结束日期
            LocalDate endDate = startDate.plusMonths(monthsToAdd);

            // 格式化并拼接开始和结束日期
            return endDate.format(formatter);

        } catch (NumberFormatException e) {
            // 如果月份数不是有效的整数，则返回错误消息
            return "无效的月份数：" + monthsToAddStr;
        }
    }

    @Override
    public Result deleteSecondmentInformation(Long id) {
        secondmentContentInfoMapper.deleteById(id);
        return Result.ok("删除成功！");
    }

    @Override
    public Result getExcelNames(Long secondmentId) {
        SecondmentInfoDTO secondmentInfoDTO = new SecondmentInfoDTO();
        secondmentInfoDTO.setSecondmentId(secondmentId);
        String headers = secondmentHeadInfoMapper.getHeadersBySecondmentId(secondmentId);
        if (headers == null) {
            return Result.fail("请先上传excel文件！");
        }
        Map map = JSON.parseObject(headers, Map.class);
        Integer idx = -1;
        for (Object key : map.keySet()) {
            if(map.get(key).equals(Constant.excelDepartmentTag)) {
                idx = Integer.parseInt(key.toString());
            }
        }

        List<SecondmentInfoVO> secondmentInfoVOList = secondmentContentInfoMapper.getFieldsValueBySecondmentId(secondmentInfoDTO);
//        Set<Object> departmentNames = new LinkedHashSet<>();
        Map<String,Long> departmentInfoMap = new HashMap<String,Long>();
        for (SecondmentInfoVO secondmentInfoVO : secondmentInfoVOList) {
            Map afterValue = JSON.parseObject(secondmentInfoVO.getFieldsValue(), Map.class);
            Object departmentName = afterValue.get(idx);
            Long levelId = departmentMapper.getLevelIdByName(departmentName.toString());
            departmentInfoMap.put(departmentName.toString(),levelId);
        }
        return Result.ok(departmentInfoMap);
    }

    @Override
    public Result changeState(StateDTO stateDTO) {
        // 这里进行校验 如果是不同意 可以直接写入数据库 如果同意 需要校验 并且返回相关校验失败字段

        // 1.本职级被借调次数不超过两次

        // 2.同一任务外，两次借调间隔不少于一年

        // 3.同时被借调的人数不超过单位编制人数的百分之2
        secondmentContentInfoMapper.changeState(stateDTO);
        return Result.ok("成功！");
    }

    @Override
    public Result changeTip(TipDTO tipDTO) {
        secondmentContentInfoMapper.changeTip(tipDTO);
        return Result.ok("成功！");
    }

    @Override
    public Result cancelConfirm(Long id) {
        secondmentContentInfoMapper.setConfirm(id);
        SecondmentContentInfo secondmentContentInfo = secondmentContentInfoMapper.getById(id);
        UserInfo userInfo = new UserInfo();
        userInfo.setName(secondmentContentInfo.getUserName());
        userInfo.setUserId(secondmentContentInfo.getUserId());
        userInfoMapper.cancelSecondment(userInfo);

        TaskList taskList = new TaskList();
        taskList.setName(secondmentContentInfo.getUserName());
        //taskList.setUserId(secondmentContentInfo.getUserId());
        taskList.setSecondmentId(secondmentContentInfo.getSecondmentId());
        taskListMapper.cancelSecondment(taskList);
        return Result.ok("取消成功！");
    }
}
